const JWT = require("jsonwebtoken");
const { secret } = require("./config");

// 验证token的中间件
const validateToken = async (ctx, next) => {
  const whiteList = ["/login", "/register", "/refresh/token", "/login/long"];
  const regWhiteList = [/\/product\/.+/]
  console.log('path-----', ctx.path)
  console.log('url-----', ctx.url)
  if (whiteList.includes(ctx.path) || regWhiteList.some(reg => reg.test(ctx.path))) {
    await next();
  } else {
    const token = ctx.headers.authorization; // 从headers获取token
    if (!token) {
      ctx.body = {
        code: 401,
        message: "token 不可以为空！！！",
      };
      return;
    }
    const accessToken = token.slice(7);
    try {
      const user = JWT.verify(accessToken, secret);
      ctx.state.user = user;
      await next();
    } catch {
      ctx.body = {
        code: 401,
        message: "token 解析失败",
      };
      return;
    }
  }
};

module.exports = {
  validateToken,
};
